<template>
  <div class="content">
    <el-form ref="form" :model="form" label-width="80px" :inline="true">
      <el-form-item>
        <el-select clearable v-model="form.statusChecked" placeholder="请选择查询条件" size="mini" style="width:150px">
          <el-option label="姓名" value="1"></el-option>
          <el-option label="学号" value="2"></el-option>
          <el-option label="证件号" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input clearable v-model="form.statusValue" size="mini" placeholder="请输入姓名/学号/证件号" style="width:150px"></el-input>
      </el-form-item>

      <el-form-item>
        <el-input clearable v-model="form.phone" size="mini" placeholder="请输入手机号" style="width:150px"></el-input>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          :disabled="disableSchool"
          v-model="form.deptId"
          @change="gradeList(form.deptId)"
          placeholder="请选择所属学校"
          size="mini"
          style="width:150px"
        >
          <el-option :label="item.name" :value="item.id" v-for="item in schoolList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          v-model="form.glassId"
          @change="classList(form.glassId)"
          placeholder="请选择年级"
          size="mini"
          style="width:150px"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in gradeData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select clearable v-model="form.classId" placeholder="请选择班级" size="mini" style="width:150px">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in classData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
        <el-select clearable v-model="form.status" placeholder="请选择状态" size="mini" style="width:150px">
          <el-option label="正常" value="1"></el-option>
          <el-option label="转学" value="2"></el-option>
          <el-option label="开除" value="3"></el-option>
          <el-option label="借读" value="4"></el-option>
        </el-select>
      </el-form-item> -->
      <el-button type="primary" size="mini" class="btn" @click="search"><i class="fa fa-search" style="margin-right:5px;"></i>查询</el-button>
      <!-- <el-button type="primary" size="mini" @click="editAddOrUpdate(1)"><i class="fa fa-plus" style="margin-right:5px;"></i>新增</el-button>
      <el-button type="primary" size="mini" @click="downLoadDemo" style="margin-right:10px"><i class="fa fa-arrow-down" style="margin-right:5px;"></i>下载</el-button>

      <el-upload
        class="upload"
        :action="url+'/admin/student/upload'"
        :on-success="uploadSuccess"
        :headers="requestHeader"
        :limit="100"
        accept="xlsx"
        :show-file-list="false"
        :on-exceed="handleExceed"
      >
      <el-button size="mini" type="primary" style="margin-right:10px"><i class="fa fa-arrow-up" style="margin-right:5px;"></i>导入</el-button>
      </el-upload>
      <el-button type="primary" size="mini" @click="excelExport"><i class="fa fa-arrow-down" style="margin-right:5px;"></i>导出</el-button> -->
      <!--
      <el-button type="primary" size="mini">创建学生照片</el-button>
      <el-button type="primary" size="mini">导出学生信息</el-button>-->
    </el-form>

    <!-- <el-divider></el-divider> -->
    <template>
      <el-table :data="tableData" v-loading="loading" size="mini" style="width: 100%;margin-top:30px">
        <el-table-column prop="id" fixed label="学生ID" width="150"></el-table-column>
        <el-table-column prop="name" fixed label="姓名"></el-table-column>
        <el-table-column prop="gradeName" label="年级"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="balance" label="余额"></el-table-column>
        <el-table-column prop="phone" width="100" label="联系电话"></el-table-column>
        <el-table-column prop="idNo" width="150" label="身份证号"></el-table-column>
        <el-table-column prop="gender" label="性别"></el-table-column>
        <el-table-column prop="nation" label="民族"></el-table-column>
        <el-table-column prop="guardian" label="监护人"></el-table-column>
        <el-table-column prop="nativePlace" label="籍贯"></el-table-column>
        <el-table-column prop="address" width="150" label="家庭住址"></el-table-column>

        <el-table-column prop="dormitoryFlg" label="是否住校">
          <template slot-scope="scope">
            <span>{{scope.row.dormitoryFlg===true?"住校":'走读'}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span>{{scope.row.status==1?"在校":'毕业'}}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" :label="$t('action.operation')" width="210">
          <template slot-scope="scope">
<!--            <el-button size="mini" @click="editAddOrUpdate(2,scope.row.id)"><i class="fa fa-edit" style="margin-right:5px;"></i>{{$t('action.edit')}}</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            ><i class="fa fa-trash" style="margin-right:5px;"></i>{{$t('action.delete')}}</el-button>-->
            <el-button
              size="mini"
              type="danger"
              @click="handleUpdate(scope.$index, scope.row)"
            ><i class="fa fa-trash" style="margin-right:5px;"></i>恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-row>
      <el-col :span="24">
        <el-pagination
          style="float:right;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 15, 20,50,100]"
          :page-size="everyPageNum"
          layout="total, sizes,prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
        <div class="grid-content bg-purple-dark" style="font-size:13px;float:right;margin:26px 0 0 10px">合计金额：<span style="color:rgb(20, 136, 154);font-weight:bold">{{sumData}}</span></div>
      </el-col>
    </el-row>
    <!-- <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20,50,100]"
      :page-size="everyPageNum"
      layout="total, sizes,prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination> -->
    <!--新增编辑弹框-->
    <el-dialog :title="updateStatus==1?'创建学生信息':'编辑学生信息'" :visible.sync="showEdit" width="60%" v-dialogDrag>
      <editStudent @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></editStudent>
    </el-dialog>
    <!-- <el-row>
      <el-col :span="24"><div class="grid-content bg-purple-dark">合计金额：111</div></el-col>
    </el-row> -->
  </div>
</template>

<script>
import Cookies from "js-cookie";
import editStudent from "@/components/StudentManagement/edit";

export default {
  name: "StudentManagement",
  components: {
    editStudent
  },
  data() {
    return {
      url: this.$Config.url,
      showEdit: false, //显示编辑弹框
      updateStatus: 1, //默认是新增
      loading: false,
      deptId: "", //学校id
      total: 1, //总页数
      everyPageNum: 10, //每页多少条
      currentPage: 1, //当前页
      form: {
        statusChecked: "",
        statusValue: "",
        glassId: "",
        classId: "",
        status: "2",
        deptId: "",
        phone:""
      },
      tableData: [],
      gradeData: [], //年级列表
      classData: [], //班级列表
      schoolList: [], //学校数据
      requestHeader: {
        "x-baie-admin-token": Cookies.get("token")
      },
      disableSchool: false,
      sumData: ''
    };
  },
  mounted() {
    this.common();
    this.getSchool();
    const userInfo = JSON.parse(localStorage.getItem("userInfo")).deptId;
    if (userInfo == null || userInfo == "") {
      this.disableSchool = false;
    } else {
      this.form.deptId = userInfo;
      this.disableSchool = true;
      this.gradeList(userInfo);
    }
  },
  methods: {
    getSchool() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    downLoadDemo() {
      const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
      // if (JSON.parse(localStorage.getItem("userInfo")).deptId) {
        var divFrame = window.parent.document.getElementById(
          "downLoadListFrame"
        );
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame);
        }
        var iframe = window.parent.document.createElement("iframe");
        iframe.setAttribute("id", "downLoadListFrame");
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe);
        divFrame = window.parent.document.getElementById("downLoadListFrame");
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = this.url + "/admin/excel/student?deptId=" + deptId;
        divFrame.style.display = "none";
      // } else {
      //   this.$message({
      //     message: "超级管理员无法下载模板",
      //     type: "warning"
      //   });
      // }
    },
    excelExport() {
      const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
      // if (JSON.parse(localStorage.getItem("userInfo")).deptId) {
        var divFrame = window.parent.document.getElementById(
          "downLoadListFrame"
        );
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame);
        }
        var iframe = window.parent.document.createElement("iframe");
        iframe.setAttribute("id", "downLoadListFrame");
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe);
        divFrame = window.parent.document.getElementById("downLoadListFrame");
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = `${this.url}/admin/student/export?name=${this.form.statusChecked == 1 ? this.form.statusValue : ""}&studentNo=${this.form.statusChecked == 2 ? this.form.statusValue : ""}&idNo=${this.form.statusChecked == 3 ? this.form.statusValue : ""}&status=${this.form.status}&gradeId=${this.form.glassId}&classId=${this.form.classId}&phone=${this.form.phone}`;
        divFrame.style.display = "none";
      // } else {
      //   this.$message({
      //     message: "超级管理员无法下载模板",
      //     type: "warning"
      //   });
      // }
    },
    uploadSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.$message({
          message: "导入成功",
          type: "success"
        });
        this.common(this.currentPage, this.everyPageNum);
      } else {
        this.$message({
          message: response.msg,
          type: "error"
        });
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    gradeList(id) {
      const that = this;
      this.$axios
        .get(that.url + "/admin/grade/list", {
          params: {
            deptId: id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.gradeData = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    classList(id) {
      const that = this;
      that.form.classId = "";
      this.$axios
        .get(that.url + "/admin/class/list", {
          params: {
            gradeId: id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.classData = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    search() {
      this.common(this.currentPage, this.everyPageNum);
    },
    handleDelete(index, row) {
      this.$confirm("您确认要删除该学生?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteStudent(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    deleteStudent(id) {
      const that = this;
      this.$axios
        .post(
          that.url + "/admin/student/delete/{id}",
          that.$qs.stringify({ id }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "删除成功!"
            });
            that.common(that.currentPage, that.everyPageNum);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },


    handleUpdate(index, row) {
      this.$confirm("您确认要恢复该学生?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.updateStudent(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消恢复"
          });
        });
    },
    updateStudent(id) {
      const that = this;
      this.$axios
        .post(
          that.url + "/admin/student/update/{id}",
          that.$qs.stringify({ id }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "恢复成功!"
            });
            that.common(that.currentPage, that.everyPageNum);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    editAddOrUpdate(status, id) {
      //新增或编辑
      /**
       * 1是新增
       * 2是编辑
       */
      this.showEdit = true;
      if (status == 1) {
        //新增
        this.updateStatus = 1;
        setTimeout(() => {
          this.$refs["child"].resetForm("ruleForm");
        }, 0);
      } else {
        //编辑
        this.updateStatus = 2;
        setTimeout(() => {
          this.$refs["child"].resetData(id);
        }, 0);
      }
    },
    handleSizeChange(val) {
      //   每页多少条
      this.everyPageNum = val;
      this.common(this.currentPage, val);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.common(val, this.everyPageNum);
    },
    hideEditStatus(status) {
      this.showEdit = false;
      this.common(this.currentPage, this.everyPageNum);
    },
    common(pageNo = 1, pageSize = 10) {
      const that = this;
      that.loading = true;
      this.$axios
        .get(that.url + "/admin/student/page", {
          params: {
            pageNo,
            pageSize,
            name: that.form.statusChecked == 1 ? that.form.statusValue : "",
            studentNo:
              that.form.statusChecked == 2 ? that.form.statusValue : "",
            idNo: that.form.statusChecked == 3 ? that.form.statusValue : "",
            status: that.form.status,
            gradeId: that.form.glassId,
            classId: that.form.classId,
            phone:that.form.phone
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          that.loading = false;
          if (res.data.code == 200) {
            that.tableData = res.data.data.records;
            that.total = res.data.data.total;
            that.sumData = res.data.sum;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.loading = false;
          console.log(error);
        });
    },
    handleClick(row) {
      console.log(row);
    }
  }
};
</script>

<style scoped lang="scss">
.upload {
  display: inline-block;
}
.el-pagination {
  float: right;
  margin: 20px 10px;
}
.button_list {
  margin-bottom: 10px;
}

.content {
  text-align: left;
}

.el-divider {
  margin: 10px 0;
}

.btn {
  margin-top: 6px;
}

.el-form-item {
  margin-bottom: 0;
}
</style>
